package com.example.contactpicker;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

@SuppressWarnings("deprecation")
public class ContactPicker extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_picker);

		ContentResolver cont = getContentResolver();

		final Cursor c = cont.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
				null, null);

		Log.d("numar", ContactsContract.CommonDataKinds.Phone.CONTENT_URI.toString());
		
		String[] from = new String[] {
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };

		int[] to = new int[] { R.id.namelist, R.id.phonelist };

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
				R.layout.listitem, c, from, to);

		ListView lv = (ListView) findViewById(R.id.listView1);
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				c.moveToPosition(arg2);

				String name = c.getString(c
						.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

				String phone = c.getString(c
						.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

				Intent outData = new Intent();
				outData.putExtra("name", name);
				outData.putExtra("phone", phone);
				setResult(Activity.RESULT_OK, outData);
				finish();

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.contact_picker, menu);
		return true;
	}

}
